/*
 * Copyright (c) 2005, 2022, EVECOM Technology Co.,Ltd. All rights reserved.
 * EVECOM PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.ruoyi.community.controller.wxApi;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.community.constant.WxMaConstants;
import com.ruoyi.community.domain.User;
import com.ruoyi.community.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <P><B>Description: </B>TODO 添加描述</P>
 * Revision Trail: (Date/Author/Description)
 * 2022/2/24 LuoYi CREATE
 *
 * @author LuoYi
 * @version 1.0
 */
@RestController
@RequestMapping("/wx/mp")
@Api(tags = {"登录"})
public class WxLoginController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private WxMpService wxService;

    @Value("${wechat.redirect_uri}")
    public String redirect_uri;
    //="https://zhsq.fjclound.com/#/pages/my/index"
    private final String scope="snsapi_userinfo";
    @Value("${wechat.AppId}")
    public String AppId;

    @ApiOperation("wx登录")
    @GetMapping("/login")
    public AjaxResult login(String code) throws WxErrorException {
         WxMpOAuth2AccessToken accessT = wxService.oauth2getAccessToken(code);
         WxMpUser wxMpUser = wxService.oauth2getUserInfo(accessT,null);
         redisCache.setCacheObject(WxMaConstants.TOKEN_OPENID_BEGIN+":"+accessT.getOpenId(),wxMpUser,10, TimeUnit.HOURS);
        System.out.println(code);
        User user = new User();

        user.setWeixinOpenid(wxMpUser.getOpenId());
        List<User> users = userService.selectUserList(user);
        if(users.size()==0){
           // userService.insertUser(user);
            return AjaxResult.successMe(10000,"未注册",wxMpUser);
        }
        return AjaxResult.successMe(10001,"已注册",wxMpUser);

    }
    @ApiOperation("获取网页授权地址")
    @GetMapping("/oauth2/geturl")
    public AjaxResult getParam(){

      return AjaxResult.success("成功",wxService.oauth2buildAuthorizationUrl(redirect_uri,scope,"abc123"));
    }




}
